package db

import ext.currentDateStr
import ext.currentTimestamp
import ext.log
import manager.DataBaseManager
import org.json.JSONObject
import java.io.IOException


/**
 * 上报库存时所需要数据
 */
class Order(
    val waresId: String,
    val waresName: String,
    val waresPrice: Double,
    val waresCargo: String,
    val deliverySign: Boolean, // 出货是否成功
    val payMethod: String = "card",
    val dateStr: String = currentDateStr(),
    val timestamp: Long = currentTimestamp()
) {
    companion object {

        const val TABLE_NAME = "db_table_order"

        const val TABLE_CREATE_SQL = "create table if not exists $TABLE_NAME (" +
                "id integer primary key autoincrement, " +
                "wares_id varchar(30), " +
                "wares_name varchar(100), " +
                "wares_price double, " +
                "wares_cargo varchar(10), " +
                "delivery_sign integer, " +
                "pay_method varchar(30), " +
                "date_str varchar(50), " +
                "timestamp integer )"

        const val TABLE_INSERT_SQL = "insert into $TABLE_NAME ( " +
                "wares_id, " +
                "wares_name, " +
                "wares_price, " +
                "wares_cargo, " +
                "delivery_sign, " +
                "pay_method, " +
                "date_str, " +
                "timestamp) " +
                "values(?, ?, ?, ?, ?, ?, ?, ?)"

        const val TABLE_DELETE_SQL = "delete from $TABLE_NAME where id = ?"

        const val TABLE_QUERY_SQL = "select * from $TABLE_NAME"

        const val TABLE_DROP_SQL = "drop table if exists ${TABLE_NAME}"

        fun createTable() {
            val db = DataBaseManager.Instance.writableDatabase
            db.execSQL(TABLE_CREATE_SQL)
            db.close()
            log("创建订单表")
        }

        fun dropTable() {
            val db = DataBaseManager.Instance.writableDatabase
            db.execSQL(TABLE_DROP_SQL)
            db.close()
            log("删除订单表")
        }

        fun withDatabase(): ArrayList<Order> {
            val list = ArrayList<Order>()
            val db = DataBaseManager.Instance.writableDatabase
            try {
                val cursor = db.rawQuery(TABLE_QUERY_SQL, null)
                while (cursor.moveToNext()) {
                    val id = cursor.getInt(0)
                    val waresId = cursor.getString(1)
                    val waresName = cursor.getString(2)
                    val waresPrice = cursor.getDouble(3)
                    val waresCargo = cursor.getString(4)
                    val sign = cursor.getInt(5)
                    val payMethod = cursor.getString(6)
                    val dateStr = cursor.getString(7)
                    val timestamp = cursor.getLong(8)
                    val deliverySign = if (sign > 0) true else false
                    val order = Order(
                        waresId,
                        waresName,
                        waresPrice,
                        waresCargo,
                        deliverySign,
                        payMethod,
                        dateStr,
                        timestamp
                    )
                    order.id = id
                    log("找到一个订单:${order}")
                    list.add(order)
                }
                cursor.close()
            } catch (e: Exception) {
                e.printStackTrace()
                throw IOException("订单查找异常")
            } finally {
                db.close()
            }
            return list
        }
    }

    var id: Int = -1

    fun delete() {
        val db = DataBaseManager.Instance.writableDatabase
        try {
            db.execSQL(TABLE_DELETE_SQL, arrayOf(id))
            log("订单删除成功:${toString()}")
        } catch (e: Exception) {
            e.printStackTrace()
            throw IOException("订单删除失败")
        } finally {
            db.close()
        }
    }

    fun insert() {
        val db = DataBaseManager.Instance.writableDatabase
        try {
            val sign = if (deliverySign) 1 else 0
            db.execSQL(
                TABLE_INSERT_SQL, arrayOf(
                    waresId, waresName, waresPrice,
                    waresCargo, sign, payMethod,
                    dateStr, timestamp
                )
            )
            val cursor = db.rawQuery("select last_insert_rowid() from ${TABLE_NAME}", null)
            cursor.moveToFirst()
            id = cursor.getInt(0)
            cursor.close()
            log("订单插入成功:${toString()}")
        } catch (e: Exception) {
            e.printStackTrace()
            throw IOException("数据库操作失败")
        } finally {
            db.close()
        }
    }

    /**
     * 出货结果 订单
     */
    fun toJsonWithOrder(): JSONObject {
        val json = JSONObject()
        json.put("waresId", waresId)
        json.put("waresName", waresName)
        json.put("waresPrice", waresPrice)
        json.put("payMethod", payMethod)
        json.put("cargo", waresCargo)
        json.put("sign", deliverySign)
        json.put("date", dateStr)
        json.put("timestamp", timestamp)
        return json
    }

    override fun toString(): String {
        return "$id ($waresId $waresName $waresPrice $waresCargo $deliverySign $payMethod $dateStr $timestamp)"
    }
}